package com.google.cascadeusing;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;

import com.google.AbstractBaseComparision;
import com.google.cascadeusing.entity.Enrollment;
import com.google.cascadeusing.entity.Lecturer;
import com.google.cascadeusing.entity.Seminar;
import com.google.cascadeusing.entity.Student;
import com.google.lazyloading.entity.LazyShelf;
import com.google.lazyloading.entity.NormalShelf;
import com.google.utility.TimeMachine;

public class CascadeUsingComparision extends AbstractBaseComparision {

	private static int ENROLLMENT_NUMBER = 20;
	private static int SEMINAR_NUMBER = 20;
	
	static public long applyCascade() {
		TimeMachine timeMachine = new TimeMachine();
		timeMachine.start();
		
		EntityManager entityManager = createEntityManager();
		Lecturer lecturer = prepareLecturer();
		entityManager.persist(lecturer);
		
		return timeMachine.finish();
	}
	
	private static Lecturer prepareLecturer() {
		Lecturer lecturer = new Lecturer();
		lecturer.setSeminars(prepareSeminars(SEMINAR_NUMBER));
		return lecturer;
	}
	
	private static List<Seminar> prepareSeminars(int number) {
		List<Seminar> seminars = new ArrayList<Seminar>();
		for (int i = 0; i < number; i++) {
			seminars.add(prepareSeminar());
		}
		return seminars;
	}

	private static Seminar prepareSeminar() {
		Seminar seminar = new Seminar();
		seminar.setEnrollment(prepareEnrollments(ENROLLMENT_NUMBER));
		return seminar;
	}

	private static List<Enrollment> prepareEnrollments(int number) {
		List<Enrollment> enrollments = new ArrayList<Enrollment>();
		for (int i = 0; i < number; i++) {
			enrollments.add(prepareEnrollment());
		}
		return enrollments;
	}

	private static Enrollment prepareEnrollment() {
		Enrollment enrollment = new Enrollment();
		enrollment.setStudent(prepareStudent());
		return enrollment;
	}

	private static Student prepareStudent() {
		Student student = new Student();
		return student;
	}

	static public long notApplyLazyLoading() {
		TimeMachine timeMachine = new TimeMachine();
		timeMachine.start();
		
		EntityManager entityManager = createEntityManager();
		entityManager.find(NormalShelf.class, 1L);
		
		return timeMachine.finish();
	}
	
	public static void main(String[] args) {
		applyCascade();
		
		
//		long lazyPeriod = applyLazyLoading();
//		long nonLazyPeriod = notApplyLazyLoading();
//		System.out.println("Lazy loading! Time to run: " + lazyPeriod);
//		System.out.println("Non-Lazy loading! Time to run: " + nonLazyPeriod);
//		if (lazyPeriod > nonLazyPeriod) {
//			System.out.println("Lazy loading is faster.....WIN");
//		} else {
//			System.out.println("Non-Lazy loading is faster.....WIN");
//		}
	}
	
}
